package Twitim::AutoStart;

use strict;
use warnings;

my $Default_Sys_Dir = '/usr/share/applications/';
my $User_Dir        = "$ENV{'HOME'}/.config/autostart/";
my $Desktop_Entry   = 'twitim.desktop';
my $Header          = 'X-GNOME-Autostart-enabled';

binmode( STDOUT, ':utf8' );

sub new {
    my ( $this, $sys_dir ) = @_;
    my $class = ref($this) || $this;

    $sys_dir ||= $Default_Sys_Dir;
    if ( !-R $sys_dir . $Desktop_Entry ) {
        warn "Could not read the system desktop entry in $sys_dir.\n";
        $sys_dir = 0;
    }

    my $self = {
        sys_dir            => $sys_dir,
        user_dir_is_ok     => 1,
        auto_start         => 0,
        auto_start_initial => -1
    };
    bless $self, $class;

    $self->_check_user_entry;
    return $self;
}

sub is_ok {
    my $self = shift;

    my $result = $self->{'sys_dir'} && $self->{'user_dir_is_ok'} ? 1 : 0;
    # print $result . "\n";
    return $result;
}


sub get {
    my $self = shift;
    return $self->{'auto_start'};
}

sub set {
    my ( $self, $auto_start ) = @_;
    $self->{'auto_start'} = $auto_start;
}

sub end {
    my $self = shift;

    return if $self->{'auto_start'} == $self->{'auto_start_initial'};
    return if !$self->is_ok;

    my ( $data, $auto_start ) = _load( $self->{'sys_dir'} . $Desktop_Entry );
    _save( $data, $self->{'auto_start'} );
}

sub _check_user_entry {
    my $self       = shift;
    my $entry_file = $User_Dir . $Desktop_Entry;

    if ( !-d $User_Dir ) {
        if ( !mkdir $User_Dir ) {
            warn "Could not mkdir $User_Dir.\n";
            $self->{'user_dir_is_ok'} = 0;
            return;
        }
    }

    return if !-R $entry_file;

    my ( $data, $auto_start ) = _load($entry_file);
    $self->{'auto_start'} = $self->{'auto_start_initial'} = $auto_start;
}

sub _load {
    my $entry_file = shift;
    my $auto_start = 0;
    my $data;

    open my $fh, '<:utf8', $entry_file or die $!;
    while ( my $line = <$fh> ) {
        $data = $data . $line if ( $line !~ /$Header=/ );
        $auto_start = 1 if ( $line =~ /$Header=true/ );
    }
    close $fh;

    return ( $data, $auto_start );
}

sub _save {
    my ( $data, $auto_start ) = @_;
    my $entry_file = $User_Dir . $Desktop_Entry;
    my $result = $auto_start ? 'true' : 'false';

    chomp($data);

    open my $fh, '>:utf8', $entry_file or die $!;
    print $fh $data . "\n$Header=$result\n";
    # print $data . "\n$Header=$result\n";
    close $fh;
}

1;
